from flask import Blueprint,jsonify,request
from db import db1
from utils.rs import rs
import json
import datetime
from utils.myfile import get_data,post_data

bp_work = Blueprint('work',__name__)


@bp_work.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


# 获取数据源接口
@bp_work.route('/getresourcedata',methods=['POST','GET'])
def getresourcedata():
    if request.method == 'GET':
        # 从redis取,如果有直接返回
            values = rs.get_str('dataresouce')
            if values:
                list = eval(values)
            else:
                # 如果没有查询
                sql = "select * from data_source"
                res = db1.find_all(sql)
                list = []
                if res:
                    list = eval(values)
                    for i in res:
                        dict={'id':i['id'],'name':i['name']}
                        sql1 = "select id,name,type from %s"%(i['tablename'])
                        subres = db1.find_all(sql1)
                        dict['mes'] = subres
                        list.append(dict)
                #存入redis
                rs.set_str('dataresouce',json.dumps(list))
            return jsonify({"code":200,'list':list})
    else:
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update workflow set params='%s' where id=%d"%(data['mes'],int(data['id']))
        print(sql)
        db1.update(sql)
        res = db1.find_all(sql)
        return jsonify({"code":200})

        
@bp_work.route('/getworkf')
def getworkf():
    id = request.args.get('id')
    sql = "select * from workflow where id=%d"%(int(id))
    res = db1.find(sql)
    return jsonify({"code":200,'workf':res})


def getdeptdata(data):
    tree = {}
    list=[]
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if not pid:
            j['type']=1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children']=[]
            #查询此部门下所有员工
            sql = "select * from users where dept_id=%d"%(j['id'])
            res = db1.find_all(sql)
            userlist=[]
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type']=2
            tree[pid]['children'].append(j)

    return list

@bp_work.route('/getcomanyuser')
def getcomanyuser():
    #获取所有公司及所有部门
    sql = "select * from dept"
    res = db1.find_all(sql)
    mes = getdeptdata(res)
    return jsonify({'code':200,'list':mes})
    #数据重组，查询员工
@bp_work.route('/taskm',methods=['POST','GET'])
def taskm():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form

        title = data['title']
        params = data['params']
        auditids = data['auditids']
        #添加任务
        sql = "insert into task(title,params,next_audit,status,nexta) values('%s','%s','%s',1,%d)"%(title,params,auditids,auditids[0])
        db1.update(sql)
        db1.commit()
        sql1 = "select id,title from task where title='%s'"%(title)
        task = db1.find(sql1)
        #把当前任务加到redis中，选用hash类型
        key='task%d'%(auditids[0])
        rs.insert_hash(key,task['id'],task['title'])
        return jsonify({"code":200})
    else:
        # 通过任务id获取任务信息及对应的审批信息
        userid = request.args.get('userid')
        if userid:
            sql = "select * from task where userid=%d"%(int(userid))
            res = db1.find_all(sql)
            return jsonify({"code":200,'list':res})
        id = request.args.get('id')
        # id=3
        sql = "select * from task where id=%d"%(int(id))
        print(sql)
        task = db1.find(sql)
        # 此任务相关的审批任务
        sql1 = "select * from audit_record where taskid=%d"%(int(id))
        print(sql1)
        records = db1.find_all(sql1)
        task['audit_records'] = records
        return jsonify({'code':200,'task':task})


#待我审批
@bp_work.route('/mytaskaudit')
def mytaskaudit():
    id = request.args.get('id')
    #从redis中获取我的任务列表
    key='task%d'%(int(id))
    task = rs.get_all_hash(key)
    list=[]
    for k,v in task.items():
        id = str(k,encoding='utf8')
        title = str(v,encoding='utf8')
        list.append({'id':id,'title':title})

    return jsonify({"code":200,'list':list})

@bp_work.route('/taskrecordM',methods=['POST'])
def taskrecordM():
    data = get_data()
    #写审批记录表
    time = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    try:
        sql = "insert into audit_record(taskid,userid,username,is_agree,reason,add_time) values(%d,%d,'%s',%d,'%s','%s')"%(int(data['taskid']),int(data['userid']),data['username'],int(data['agree']),data['reason'],time)
        db1.update(sql)
        db1.commit()
    except:
        return jsonify({'code':10010,'mes':'审批失败'})
    #判断是否同意
    tsql = "select * from task where id=%d"%(int(data['taskid']))
    task = db1.find(tsql)
    key='task%d'%(int(data['userid']))
    #清除当前redis中的信息
    rs.del_hash(key,int(data['taskid']))
    auditlist = json.loads(task['next_audit'])
    index = auditlist.index(int(data['userid'])) # 忘记加int了
    if data['agree'] == '1':
        try:
            #同意，查询任务，更新下一审批人，redis清除当前审批人，加入下一审批人，
            #任务表中更新任务状态，如果是最后一个审批人，查新成已经完成，其它审核中
            if index == len(auditlist)-1:
                sql1 = "update task set status=3,nexta=0 where id=%d"%(int(data['taskid']))
                db1.add(sql1)
            else:
                sql1 = "update task set status=2,nexta=%d where id=%d"%(auditlist[index+1],int(data['taskid']))
                db1.add(sql1)
                #添加redis
                newkey='task%d'%(int(auditlist[index+1]))
                #把下一审批人加入到redis
                rs.insert_hash(newkey,int(data['taskid']),task['title'])
            db1.commit()   
        except:
            db1.rollback()
            return jsonify({"code":10020,'mes':'失败'})
    else:
        #不同意，把redis中当前审批人清除，任务表中的下一审批人清空
        if index == 0:
            sql1 = "update task set status=1,nexta=0 where id=%d"%(int(data['taskid']))
            db1.update(sql1)
        else:
            sql1 = "update task set nexta=%d where id=%d"%(int(auditlist[index-1]),int(data['taskid']))
            db1.update(sql1)
            #添加redis
            newkey='task%d'%(int(auditlist[index-1]))
            #把下一审批人加入到redis
            rs.insert_hash(newkey,int(data['taskid']),task['title'])
    return jsonify({"code":200})
    

@bp_work.route('/userlist')
def userlist():
    sql = "select d.name,u.username,u.id,u.password,u.utype from users as u left join dept as d on u.dept_id=d.id"
    res = db1.find_all(sql)
    return jsonify({'code': 200, 'list': res})


@bp_work.route('/post_Message', methods=['POST','GET'])
def post_Message():

    if request.method=='GET':
        sql = "select * from message"
        res = db1.find_all(sql)
        return jsonify({'code': 200, 'list': res})
    else:
        data = post_data()
        userlist1 = json.dumps(data['userlist'],ensure_ascii=False)
        # try:q
        if len(data['userlist']) > 0:
            sql = "insert into message(title,content,status,designate,type,stime,etime,priority,userlist) values('%s','%s',1,%d,%d,'%s','%s',%d,'%s')" % (
                data['title'], data['content'], int(data['designate']), int(data['type']), data['stime'],
                data['etime'],int(data['priority']), userlist1)
        else:
            sql = "insert into message(title,content,status,designate,type,stime,etime,priority) values('%s','%s',1,%d,%d,'%s','%s',%d)" % (
                data['title'], data['content'], int(data['designate']), int(data['type']), data['stime'],
                data['etime'],
                int(data['priority']))
        db1.add(sql)
        db1.commit()
        return jsonify({'code': 200, 'msg': '添加成功'})
        # except:
        #     db1.rollback()
        #     # db1.commit()
        #     return jsonify({'code': 10010, 'msg': '添加失败'})